package com.lenovo.smarttraffic;

import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.design.widget.BottomNavigationView;
import android.support.design.widget.NavigationView;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.Toolbar;
import android.view.MenuItem;
import android.view.View;
import android.widget.TextView;

import com.google.gson.Gson;
import com.lenovo.smarttraffic.ui.activity.BaseActivity;
import com.lenovo.smarttraffic.ui.activity.Item1Activity;
import com.lenovo.smarttraffic.ui.activity.LoginActivity;
import com.lenovo.smarttraffic.ui.activity.SmartTrafficActivity;
import com.lenovo.smarttraffic.ui.activity.stage2.CarTsActivity;
import com.lenovo.smarttraffic.ui.activity.stage3.EnvIndicateActivity;
import com.lenovo.smarttraffic.ui.activity.stage3.ForecastActivity;
import com.lenovo.smarttraffic.ui.activity.stage4.DataAnalyzeActivity;
import com.lenovo.smarttraffic.ui.activity.stage4.UserCenterActivity;
import com.lenovo.smarttraffic.ui.activity.stage5.RoadFindActivity;
import com.lenovo.smarttraffic.ui.activity.stage6.PayCenterActivity;
import com.lenovo.smarttraffic.ui.activity.stage8.TravelHelperActivity;
import com.lenovo.smarttraffic.ui.fragment.DesignFragment;
import com.lenovo.smarttraffic.ui.fragment.MainContentFragment;
import com.lenovo.smarttraffic.util.ToastUtils;

import java.util.Map;

import de.hdodenhof.circleimageview.CircleImageView;

/**
 * @author Amoly
 * @
 * @date 2019/4/11.
 * description：
 */
public class MainActivity extends BaseActivity implements NavigationView.OnNavigationItemSelectedListener, View.OnClickListener {


    private Toolbar mToolbar;
    private DrawerLayout mDrawer;
    private MainContentFragment mMainContent;
    private DesignFragment mDesignFragment;
    private static final String POSITION = "position";
    private static final String SELECT_ITEM = "bottomItem";
    private static final int FRAGMENT_MAIN = 0;
    private static final int FRAGMENT_DESIGN = 1;
    private BottomNavigationView bottom_navigation;

    private NavigationView navigationView;
    private TextView mTitleHead;
    private TextView mTextView;

    public static String userName = "admin";


    //    private int position;

    @Override
    protected int getLayout() {
        return R.layout.activity_main;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        initView();
        initData();
        initUser();
        if (savedInstanceState != null) {
            loadMultipleRootFragment(R.id.container, 0, mMainContent, mDesignFragment);   //使用fragmentation加载根组件
            // 恢复 recreate 前的位置
            showFragment(savedInstanceState.getInt(POSITION));
            bottom_navigation.setSelectedItemId(savedInstanceState.getInt(SELECT_ITEM));
        } else {
            showFragment(FRAGMENT_MAIN);
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        initUser();
    }

    private void showFragment(int index) {
//        position = index;
        FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
        hideFragment(ft);
        switch (index) {
            case FRAGMENT_MAIN:
                mToolbar.setTitle(R.string.title_main);
                if (mMainContent == null) {
                    mMainContent = MainContentFragment.getInstance();
                    ft.add(R.id.container, mMainContent, MainContentFragment.class.getName());
                } else {
                    ft.show(mMainContent);
                }
                break;
            case FRAGMENT_DESIGN:
                mToolbar.setTitle(R.string.creative_design);
                if (mDesignFragment == null) {
                    mDesignFragment = DesignFragment.getInstance();
                    ft.add(R.id.container, mDesignFragment, DesignFragment.class.getName());
                } else {
                    ft.show(mDesignFragment);
                }
                break;
        }
        ft.commit();

    }

    private void hideFragment(FragmentTransaction ft) {
        // 如果不为空，就先隐藏起来
        if (mMainContent != null) {
            ft.hide(mMainContent);
        }
        if (mDesignFragment != null) {
            ft.hide(mDesignFragment);
        }
    }

    private void initView() {
        mToolbar = findViewById(R.id.toolbar_main);
        mDrawer = findViewById(R.id.drawer_layout);
        navigationView = findViewById(R.id.nav_view);
        bottom_navigation = findViewById(R.id.bottom_navigation);
        CircleImageView imageView = navigationView.getHeaderView(0).findViewById(R.id.ivAvatar);

        setSupportActionBar(mToolbar);
        imageView.setOnClickListener(this);
        /*设置选择item监听*/
        navigationView.setNavigationItemSelectedListener(this);

        View view = navigationView.getHeaderView(0);
        mTitleHead = view.findViewById(R.id.title_head);
        mTextView = view.findViewById(R.id.header_user);

    }

    private void initData() {
        ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
                this, mDrawer, mToolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
        toggle.syncState();
        mDrawer.addDrawerListener(toggle);
        bottom_navigation.setOnNavigationItemSelectedListener(item -> {
            switch (item.getItemId()) {
                case R.id.action_main:
                    showFragment(FRAGMENT_MAIN);
                    break;
                case R.id.action_creative:
                    showFragment(FRAGMENT_DESIGN);
                    break;
            }
            return true;
        });

    }

    private void initUser() {
        //给侧边栏设置个人信息
        SharedPreferences sharedPreferences = getSharedPreferences(Constant.LOGIN_INFO, MODE_PRIVATE);
        String loginInfo = sharedPreferences.getString(Constant.LOGIN_INFO, null);
        if (loginInfo != null) {
            Map map = new Gson().fromJson(loginInfo, Map.class);
            mTitleHead.setText((userName = map.get("account").toString()));
            mTextView.setText(String.format("您好，%s", map.get("account").toString()));
        } else {
            mTitleHead.setText("联想智能交通系统");
            mTextView.setText("点击头像登录");
        }
    }

    @Override
    public void onBackPressedSupport() {
        if (mDrawer.isDrawerOpen(GravityCompat.START)) {    /*打开或关闭左边的菜单*/
            mDrawer.closeDrawer(GravityCompat.START);
        } else {
//            super.onBackPressedSupport();
            showExitDialog();
        }
    }

    /*是否退出项目*/
    private void showExitDialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("提示");
        builder.setMessage("确定退出吗");
        builder.setNegativeButton("取消", null);
        builder.setPositiveButton("确定", (dialogInterface, i) -> InitApp.getInstance().exitApp());
        builder.show();
    }

    @Override
    public boolean onNavigationItemSelected(@NonNull MenuItem item) {
        /*设置选中item事件*/
        int id = item.getItemId();
        switch (id) {
            case R.id.nav_account:
                startActivity(new Intent(this, com.lenovo.smarttraffic.ui.activity.stage7.UserCenterActivity.class));
                break;
            case R.id.item_weather:
                if (userName.equals("null")) {
                    ToastUtils.showToast(this, "您未登录，请登录后查看");
                } else {
                    startActivity(new Intent(this, ForecastActivity.class));
                }
                break;
            case R.id.item_pay_center:
                startActivity(new Intent(this, PayCenterActivity.class));
                break;
            case R.id.item_data_analyze:
                startActivity(new Intent(this, DataAnalyzeActivity.class));
                break;
            case R.id.item_1:
                startActivity(new Intent(this, Item1Activity.class));
                break;
            case R.id.travel_helper:
                startActivity(new Intent(this, TravelHelperActivity.class));
                break;
            case R.id.smart_traffic:
                //进入智慧交通界面
                startActivity(new Intent(this, SmartTrafficActivity.class));
                break;
            case R.id.second_stage:
                startActivity(new Intent(this, CarTsActivity.class));
                break;
            case R.id.stage_three:
                startActivity(new Intent(this, EnvIndicateActivity.class));
                break;
            case R.id.stage_four:
                startActivity(new Intent(this, UserCenterActivity.class));
                break;
            case R.id.stage_five:
                startActivity(new Intent(this, RoadFindActivity.class));
                break;
            case R.id.stage_six:
                startActivity(new Intent(this, com.lenovo.smarttraffic.ui.activity.stage6.MainActivity.class));
                break;
            case R.id.stage_seven:
                startActivity(new Intent(this, com.lenovo.smarttraffic.ui.activity.stage7.DataAnalyzeActivity.class));
                break;
            case R.id.nav_setting:
                //进行dialog显示
                startActivity(new Intent(this, SettingsActivity.class));
                break;
            case R.id.nav_about:
                break;
        }

//        mDrawer.closeDrawer(GravityCompat.START);
        mDrawer.closeDrawers();
        return true;
    }


    @Override
    public void onClick(View view) {
        if (view.getId() == R.id.ivAvatar) {    /*点击头像跳转登录界面*/
            Intent intent = new Intent(this, LoginActivity.class);
            startActivity(intent);
        }
        mDrawer.closeDrawer(GravityCompat.START);
    }

}
